import router from '@/router'
import store from '@/store'
import { getToken } from '@/utils/cookie'

const whiteList = ['/login', '/register', '/forget']

router.beforeEach(async (to, from, next) => {
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      next('/index')
    } else {
      // 有token，判断是否存在用户id
      const hasUserId = store.getters.userId
      if (hasUserId) {
        next()
      } else {
        const { user_id } = await store.dispatch('user/getUserInfo')
        if (user_id) {
          next({ ...to, replace: true })
        }
      }
    }
  } else {
    if (whiteList.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
